/**
 * 剑指 Offer 39. 数组中出现次数超过一半的数字
 * https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/
 */

/**
 * @param {number[]} nums
 * @return {number}
 */
function majorityElement(nums) {
  let cur = nums[0];
  let count = 1;
  for (let i = 1; i < nums.length; i += 1) {
    if (nums[i] === cur) {
      count += 1;
    } else if (count === 1) {
      cur = nums[i];
    } else {
      count -= 1;
    }
  }
  return cur;
}

console.log(majorityElement([1, 2, 3, 2, 2, 2, 5, 4, 2]) === 2);
console.log(majorityElement([1, 2, 1]) === 1);
